package com.ryan.framework.tag.pagination;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * @summary: the filter parameter from the request by the member submitted
 * @author: ryan.guo
 */
public class PageParameterHelper implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * @summary check the string source is empty or not
	 * @param src
	 * @return boolean
	 */
	public static boolean isEmpty(String src) {
		return src == null || src.trim().equalsIgnoreCase("null") || src.trim().length() == 0;
	}

	/**
	 * @summary filter the request to get the parameter and the value when the
	 *          value is not empty
	 * @param request
	 * @return Map<ParameterName,ParameterValue>
	 */
	public static Map<String, Object> getParameters(HttpServletRequest request) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		Enumeration<?> en = request.getParameterNames();
		while (en.hasMoreElements()) {
			String paramName = (String) en.nextElement();
			String paramValue = request.getParameter(paramName);
			if (!isEmpty(paramValue)) {
				paramsMap.put(paramName, paramValue.trim());
			}
		}
		return paramsMap;
	}

	/**
	 * @summary initialize the v page object by real path and request
	 * @param pageHelper
	 * @param request
	 * @return VPage
	 */
	public static VPage initVpage(PageHelper pageHelper, HttpServletRequest request) {
		// create the page model
		VPage vpage = new VPage();
		// get the request page number, if it is null and set it is 1
		int page = ParamUtil.getInt(request, "page", 1);
		// setting default page size is 10
		int pageSize = 10;
		pageSize = pageHelper.doCustomPerPage(pageSize);
		// setting the page size for the v page
		vpage.setPageSize(pageSize);
		// setting the target page for the v page
		vpage.setTargetPage(page);
		return vpage;
	}

	/**
	 * @summary invoke the v page for the showing view
	 * @param realPath
	 * @param pageHelper
	 * @param vpage
	 */
	public static void invokeVpage(String realPath, PageHelper pageHelper, VPage vpage) {
		// setting the the path about the paging for the v page
		vpage.setRealPath(realPath);
		// setting the view for the v page
		vpage.setView(pageHelper.getPageBreakStr(vpage));
	}
	
}
